#include "completerdelegate.h"

#include "../propertyeditor.h"

#include <QtGui/QCompleter>
#include <QtGui/QLineEdit>
#include <QtGui/QStandardItemModel>

using namespace gui;

CompleterDelegate::CompleterDelegate(PropertyEditor* parent) :
    QStyledItemDelegate(parent),
    m_parent(parent),
    m_completer(0),
    m_completitionModel(0)
{
    m_completitionModel = new QStandardItemModel();
    m_completer = new QCompleter(m_completitionModel, this);
}

CompleterDelegate::~CompleterDelegate()
{

}

QWidget* CompleterDelegate::createEditor(QWidget* parent,
    const QStyleOptionViewItem& option,
    const QModelIndex& index) const
{
    QLineEdit* editor = new QLineEdit(parent);
    editor->setCompleter(m_completer);
    editor->setFrame(false);
    editor->installEventFilter(const_cast<CompleterDelegate* >(this));

    return editor;
}

void CompleterDelegate::setEditorData(QWidget* editor,
    const QModelIndex& index) const
{
    QLineEdit* _editor = qobject_cast<QLineEdit* >(editor);

    const QString property = index.data(Qt::UserRole).toString();
    const QString value = index.data().toString();
    const QVariantList options = m_parent->m_object->autocomplete(property);

    _editor->setText(value);

    m_completitionModel->clear();

    for (int i = 0; i < options.size(); ++i)
    {
        QStandardItem* item = new QStandardItem(options[i].toString());
        m_completitionModel->appendRow(item);
    }
}

void CompleterDelegate::setModelData(QWidget* editor,
    QAbstractItemModel* model,
    const QModelIndex& index) const
{
    QLineEdit* _editor = qobject_cast<QLineEdit* >(editor);

    model->setData(index, _editor->text());
}

void CompleterDelegate::updateEditorGeometry(QWidget* editor,
    const QStyleOptionViewItem& option,
    const QModelIndex& index) const
{
    editor->setGeometry(option.rect);
}
